{% extends "base.html" %}

{% block title %}系统管理 - XXXBot管理后台{% endblock %}

{% block page_title %}系统管理{% endblock %}

{% block extra_css %}
<style>
    .dashboard-stat-icon {
        height: 60px;
        width: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 12px;
        font-size: 1.5rem;
        color: white;
        margin-bottom: 0.5rem;
    }
    
    .status-dot {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        margin-right: 8px;
        background-color: #ccc;
    }
    
    .status-dot.online {
        background-color: #28a745;
    }
    
    .status-dot.offline {
        background-color: #dc3545;
    }
    
    .status-dot.waiting {
        background-color: #ffc107;
    }
    
    .stat-card {
        position: relative;
        overflow: hidden;
        margin-bottom: 1.5rem;
        border-radius: 10px;
        overflow: hidden;
        transition: all 0.3s;
    }
    
    .stat-card::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 70%);
        opacity: 0;
        transform: scale(0.5);
        transition: transform 0.5s ease, opacity 0.5s ease;
    }
    
    .stat-card:hover::before {
        opacity: 1;
        transform: scale(1);
    }
    
    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
    }
    
    .metric-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
    }
    
    .system-info-table td {
        padding: 8px;
        vertical-align: middle;
    }
    
    .system-info-table td:first-child {
        font-weight: 500;
        width: 40%;
    }
    
    .log-viewer {
        background-color: #1e1e1e;
        color: #f0f0f0;
        border-radius: 8px;
        padding: 1rem;
        font-family: 'Courier New', monospace;
        height: 400px;
        overflow-y: auto;
        margin-bottom: 1rem;
    }
    
    .log-line {
        margin: 0;
        padding: 2px 0;
        white-space: pre-wrap;
        word-break: break-all;
    }
    
    .log-line.info {
        color: #58B2DC;
    }
    
    .log-line.debug {
        color: #B0C4DE;
    }
    
    .log-line.warning {
        color: #FFD700;
    }
    
    .log-line.error {
        color: #FF6A6A;
    }
    
    .log-line.critical {
        color: #FF2400;
        font-weight: bold;
    }
    
    .log-controls {
        margin-bottom: 1rem;
    }
    
    .progress {
        height: 10px;
        border-radius: 5px;
        margin-bottom: 1rem;
    }
    
    .progress-bar {
        transition: width 0.3s ease-in-out;
    }
    
    .progress-bar[data-value]::before {
        content: attr(data-value) '%';
        position: absolute;
        right: 5px;
        color: rgba(255, 255, 255, 0.8);
        font-size: 0.75rem;
    }
    
    .card.dashboard-card {
        margin-bottom: 2rem;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        border-radius: 8px;
    }
    
    .row {
        margin-bottom: 1.5rem;
    }
    
    .col-12, .col-lg-6 {
        margin-bottom: 1.5rem;
    }
    
    #terminal-container.fullscreen {
        position: fixed;
        top: 75px;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 9999;
        height: calc(100vh - 75px) !important;
    }
    
    /* 终端iframe样式 */
    #terminal-iframe {
        width: 100%;
        height: 100%;
        border: none;
        background-color: #000;
    }
    
    /* 确保终端错误提示可见 */
    .terminal-error {
        color: #ff6b6b;
        text-align: center;
        padding: 20px;
    }
    
    /* 避免iframe内容溢出 */
    #terminal-container {
        overflow: hidden;
    }
</style>
{% endblock %}

{% block page_actions %}
<button type="button" class="btn btn-sm btn-primary me-2" id="btn-restart">
    <i class="bi bi-arrow-repeat me-1"></i>重启系统
</button>
<button type="button" class="btn btn-sm btn-outline-success" id="btn-update">
    <i class="bi bi-cloud-download me-1"></i>检查更新
</button>
{% endblock %}

{% block content %}
<div class="container-fluid p-0">
    <!-- 系统概览 -->
    <div class="row">
        <div class="col-12">
            <div class="card dashboard-card mb-4" data-aos="fade-up">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="bi bi-speedometer2 me-2 text-primary"></i>系统概览
                    </h5>
                    <span id="last-updated" class="text-muted small">最后更新: {{ system_status.time }}</span>
                </div>
                <div class="card-body px-0 py-3">
                    <div class="metric-grid px-4">
                        <!-- 运行时间 -->
                        <div class="stat-card" data-aos="fade-up" data-aos-delay="100">
                            <div class="dashboard-stat-icon" style="background: linear-gradient(135deg, #E74C3C, #C0392B);">
                                <i class="bi bi-clock-history"></i>
                            </div>
                            <h6 class="stat-title">运行时间</h6>
                            <div class="stat-value" id="uptime-value">{{ system_status.uptime|default('获取中...') }}</div>
                            <div class="stat-description" id="start-time">启动于 {{ system_status.start_time|default('--') }}</div>
                        </div>
                        
                        <!-- 内存占用 -->
                        <div class="stat-card" data-aos="fade-up" data-aos-delay="200">
                            <div class="dashboard-stat-icon" style="background: linear-gradient(135deg, #9B59B6, #8E44AD);">
                                <i class="bi bi-memory"></i>
                            </div>
                            <h6 class="stat-title">内存占用</h6>
                            <div class="stat-value" id="memory-value">{{ (system_status.memory_used / (1024*1024*1024))|round(2) }}GB / {{ (system_status.memory_total / (1024*1024*1024))|round(2) }}GB</div>
                            <div class="stat-description">
                                <div class="progress">
                                    <div class="progress-bar bg-purple memory-progress" role="progressbar" data-value="{{ system_status.memory_percent }}" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- CPU 使用率 -->
                        <div class="stat-card" data-aos="fade-up" data-aos-delay="300">
                            <div class="dashboard-stat-icon" style="background: linear-gradient(135deg, #F39C12, #D35400);">
                                <i class="bi bi-cpu"></i>
                            </div>
                            <h6 class="stat-title">CPU 使用率</h6>
                            <div class="stat-value" id="cpu-value">{{ system_status.cpu_percent|default('0') }}%</div>
                            <div class="stat-description">
                                <div class="progress">
                                    <div class="progress-bar bg-warning cpu-progress" role="progressbar" data-value="{{ system_status.cpu_percent }}" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 磁盘使用 -->
                        <div class="stat-card" data-aos="fade-up" data-aos-delay="400">
                            <div class="dashboard-stat-icon" style="background: linear-gradient(135deg, #2ECC71, #27AE60);">
                                <i class="bi bi-hdd"></i>
                            </div>
                            <h6 class="stat-title">磁盘使用</h6>
                            <div class="stat-value" id="disk-value">{{ system_status.disk_percent|default('0') }}%</div>
                            <div class="stat-description">
                                <div class="progress">
                                    <div class="progress-bar bg-success disk-progress" role="progressbar" data-value="{{ system_status.disk_percent }}" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 系统详细信息 -->
    <div class="row">
        <!-- 系统信息卡片 -->
        <div class="col-lg-6">
            <div class="card dashboard-card mb-4" data-aos="fade-up">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="bi bi-info-circle me-2 text-primary"></i>系统信息
                    </h5>
                    <button class="btn btn-sm btn-outline-primary" id="btn-refresh-system">
                        <i class="bi bi-arrow-clockwise"></i>
                    </button>
                </div>
                <div class="card-body">
                    <table class="table table-hover system-info-table">
                        <tbody>
                            <tr>
                                <td>主机名</td>
                                <td id="hostname">加载中...</td>
                            </tr>
                            <tr>
                                <td>操作系统</td>
                                <td id="platform">加载中...</td>
                            </tr>
                            <tr>
                                <td>Python版本</td>
                                <td id="python_version">加载中...</td>
                            </tr>
                            <tr>
                                <td>CPU核心数</td>
                                <td id="cpu_count">加载中...</td>
                            </tr>
                            <tr>
                                <td>总内存</td>
                                <td id="memory_total">加载中...</td>
                            </tr>
                            <tr>
                                <td>可用内存</td>
                                <td id="memory_available">加载中...</td>
                            </tr>
                            <tr>
                                <td>总磁盘空间</td>
                                <td id="disk_total">加载中...</td>
                            </tr>
                            <tr>
                                <td>可用磁盘空间</td>
                                <td id="disk_free">加载中...</td>
                            </tr>
                            <tr>
                                <td>更新时间</td>
                                <td id="update_time">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                    <div id="error_message" class="alert alert-warning" style="display: none;"></div>
                </div>
            </div>
        </div>
        
        <!-- 机器人信息卡片 -->
        <div class="col-lg-6">
            <div class="card dashboard-card mb-4" data-aos="fade-up">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="bi bi-shield-check me-2 text-primary"></i>机器人信息
                    </h5>
                </div>
                <div class="card-body">
                    <div class="bot-info-container">
                        <div class="d-flex align-items-center mb-3">
                            <div class="status-dot" id="status-dot"></div>
                            <span id="status-text" class="me-2">获取中...</span>
                            <span class="badge bg-secondary" id="status-detail">-</span>
                        </div>
                        
                        <table class="table table-hover system-info-table">
                            <tbody>
                                <tr>
                                    <td>微信昵称</td>
                                    <td id="bot-nickname">-</td>
                                </tr>
                                <tr>
                                    <td>微信ID</td>
                                    <td id="bot-wxid">-</td>
                                </tr>
                                <tr>
                                    <td>微信号</td>
                                    <td id="bot-alias">-</td>
                                </tr>
                                <tr>
                                    <td>登录设备</td>
                                    <td id="bot-device">-</td>
                                </tr>
                                <tr>
                                    <td>登录时间</td>
                                    <td id="login-time">-</td>
                                </tr>
                            </tbody>
                        </table>
                        
                        <div class="text-center mt-3">
                            <button class="btn btn-sm btn-primary me-2" id="btn-logout">
                                <i class="bi bi-box-arrow-right me-1"></i>退出登录
                            </button>
                            <button class="btn btn-sm btn-outline-secondary" id="btn-show-qrcode">
                                <i class="bi bi-qr-code me-1"></i>显示二维码
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 系统日志 -->
    <div class="row">
        <div class="col-12">
            <div class="logs-container mb-4" data-aos="fade-up">
                <div class="card dashboard-card h-100">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">
                            <i class="bi bi-journal-text me-2 text-primary"></i>系统日志
                        </h5>
                        <button class="btn btn-sm btn-outline-primary" id="btn-refresh-logs">
                            <i class="bi bi-arrow-clockwise"></i>
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <div class="d-flex">
                                <select class="form-select form-select-sm me-2" id="log-level">
                                    <option value="all">所有级别</option>
                                    <option value="debug">Debug及以上</option>
                                    <option value="info">Info及以上</option>
                                    <option value="warning">Warning及以上</option>
                                    <option value="error">Error及以上</option>
                                    <option value="critical">Critical</option>
                                </select>
                                <select class="form-select form-select-sm me-2" id="log-file">
                                    <option value="latest">最新日志</option>
                                    <option value="bot">机器人日志</option>
                                    <option value="admin">管理后台日志</option>
                                    <option value="api">API日志</option>
                                </select>
                                <span class="text-muted small ms-2 align-self-center" id="last-log-update"></span>
                            </div>
                            <div>
                                <button class="btn btn-sm btn-outline-secondary me-2" id="btn-copy-logs">
                                    <i class="bi bi-clipboard me-1"></i>复制
                                </button>
                                <button class="btn btn-sm btn-outline-secondary" id="btn-download-logs">
                                    <i class="bi bi-download me-1"></i>下载
                                </button>
                            </div>
                        </div>
                        
                        <div class="log-viewer" id="log-viewer">
                            <div class="text-center p-3"><i class="bi bi-hourglass-split me-2"></i>正在加载日志...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 终端区域 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">终端服务</h5>
                    <div>
                        <a href="/terminal" class="btn btn-sm btn-primary me-2">打开终端页面</a>
                        <a href="http://localhost:3000" target="_blank" class="btn btn-sm btn-outline-primary">直接访问终端</a>
                    </div>
                </div>
                <div class="card-body">
                    <div class="alert alert-info">
                        <h6 class="alert-heading">终端服务状态检查与操作指南</h6>
                        <hr>
                        <ol>
                            <li><strong>终端服务状态检查</strong>：在系统命令行中运行 <code>ps aux | grep wetty</code> 查看WeTTy服务是否运行</li>
                            <li><strong>访问方式</strong>：
                                <ul>
                                    <li>方式一：点击上方的<strong>打开终端页面</strong>按钮，在管理后台中使用</li>
                                    <li>方式二：点击上方的<strong>直接访问终端</strong>按钮，直接打开WeTTy服务</li>
                                </ul>
                            </li>
                            <li><strong>如果终端不可访问</strong>，请尝试重启WeTTy服务：
                                <div class="bg-dark text-light p-2 mt-1 rounded">
                                    <code>pkill -f wetty && wetty --port 3000 --host 0.0.0.0 --allow-iframe --base / --command /bin/bash &</code>
                                </div>
                            </li>
                            <li>如果重启后仍然无法访问，请检查端口3000是否已被占用：<code>netstat -tuln | grep 3000</code></li>
                        </ol>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <span class="text-muted">WeTTy终端服务端口：</span>
                            <span class="fw-bold">3000</span>
                        </div>
                        <div>
                            <button id="check-terminal" class="btn btn-sm btn-outline-primary me-2">检查终端服务状态</button>
                            <button id="restart-terminal" class="btn btn-sm btn-outline-warning">重启终端服务</button>
                        </div>
                    </div>
                    <div id="terminal-status" class="mt-3 d-none">
                        <div class="d-flex align-items-center">
                            <div class="spinner-border spinner-border-sm text-primary me-2" role="status">
                                <span class="visually-hidden">正在检查...</span>
                            </div>
                            <span>正在检查终端服务状态...</span>
                        </div>
                    </div>
                    <div id="terminal-log" class="mt-3 d-none">
                        <h6 class="text-muted">终端服务诊断日志：</h6>
                        <div class="border rounded bg-light p-2" style="max-height: 200px; overflow-y: auto; font-family: monospace; font-size: 12px; white-space: pre-wrap;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取系统信息
        function getSystemInfo() {
            // 获取系统基本信息
            fetch('/api/system/info')
                .then(response => response.json())
                .then(data => {
                    console.log('系统信息API返回数据:', data);
                    
                    if (!data.success) {
                        throw new Error(data.error || '获取系统信息失败');
                    }
                    
                    const info = data.data;
                    console.log('处理系统信息:', info);
                    
                    // 更新基本信息
                    document.getElementById('hostname').textContent = info.hostname || '未知';
                    document.getElementById('platform').textContent = info.os || info.platform || '未知';
                    document.getElementById('python_version').textContent = info.python || '未知';
                    document.getElementById('cpu_count').textContent = info.cpu_count ? (info.cpu_count + ' 核') : '未知';
                })
                .catch(error => {
                    console.error('获取系统信息失败:', error);
                    // 在错误时显示未知
                    const fields = ['hostname', 'platform', 'python_version', 'cpu_count'];
                    fields.forEach(field => {
                        const element = document.getElementById(field);
                        if (element) {
                            element.textContent = '未知';
                        }
                    });
                });

            // 获取系统状态
            fetch('/api/system/status')
                .then(response => response.json())
                .then(data => {
                    console.log('系统状态API返回数据:', data);
                    
                    if (!data.success) {
                        throw new Error(data.error || '获取系统状态失败');
                    }
                    
                    const status = data.data;
                    console.log('处理系统状态:', status);
                    
                    // 更新内存信息
                    if (status.memory_total && status.memory_used) {
                        const memoryAvailable = status.memory_total - status.memory_used;
                        document.getElementById('memory_total').textContent = formatBytes(status.memory_total);
                        document.getElementById('memory_available').textContent = formatBytes(memoryAvailable);
                        
                        // 更新内存进度条
                        const memoryPercent = status.memory_percent || ((status.memory_used / status.memory_total) * 100).toFixed(1);
                        document.getElementById('memory-value').textContent = 
                            `${formatBytes(status.memory_used)} / ${formatBytes(status.memory_total)}`;
                        const memoryBar = document.querySelector('.memory-progress');
                        if (memoryBar) {
                            memoryBar.style.width = memoryPercent + '%';
                            memoryBar.setAttribute('data-value', memoryPercent);
                        }
                    }
                    
                    // 更新CPU信息
                    if (status.cpu_percent !== undefined) {
                        document.getElementById('cpu-value').textContent = status.cpu_percent + '%';
                        const cpuBar = document.querySelector('.cpu-progress');
                        if (cpuBar) {
                            cpuBar.style.width = status.cpu_percent + '%';
                            cpuBar.setAttribute('data-value', status.cpu_percent);
                        }
                    }
                    
                    // 更新磁盘信息
                    if (status.disk_total && status.disk_used) {
                        const diskFree = status.disk_total - status.disk_used;
                        document.getElementById('disk_total').textContent = formatBytes(status.disk_total);
                        document.getElementById('disk_free').textContent = formatBytes(diskFree);
                        
                        // 更新磁盘进度条
                        const diskPercent = status.disk_percent || ((status.disk_used / status.disk_total) * 100).toFixed(1);
                        document.getElementById('disk-value').textContent = diskPercent + '%';
                        const diskBar = document.querySelector('.disk-progress');
                        if (diskBar) {
                            diskBar.style.width = diskPercent + '%';
                            diskBar.setAttribute('data-value', diskPercent);
                        }
                    }
                    
                    // 更新运行时间信息
                    if (status.uptime) {
                        document.getElementById('uptime-value').textContent = status.uptime;
                    }
                    if (status.start_time) {
                        document.getElementById('start-time').textContent = '启动于 ' + status.start_time;
                    }
                    
                    // 更新时间
                    document.getElementById('update_time').textContent = new Date().toLocaleString();
                    
                    // 隐藏错误信息
                    const errorDiv = document.getElementById('error_message');
                    if (errorDiv) {
                        errorDiv.style.display = 'none';
                    }
                })
                .catch(error => {
                    console.error('获取系统状态失败:', error);
                    const errorDiv = document.getElementById('error_message');
                    if (errorDiv) {
                        errorDiv.textContent = '获取系统状态失败: ' + error.message;
                        errorDiv.style.display = 'block';
                    }
                    
                    // 在错误时显示未知
                    const fields = ['memory_total', 'memory_available', 'disk_total', 'disk_free', 
                                  'update_time'];
                    fields.forEach(field => {
                        const element = document.getElementById(field);
                        if (element) {
                            element.textContent = '未知';
                        }
                    });
                });
        }

        // 获取机器人状态
        function updateBotStatus() {
            fetch('/api/bot/status')
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        console.error('获取状态失败:', data.error);
                        return;
                    }
                    
                    const statusData = data.data;
                    console.log('获取到状态:', statusData);
                    
                    const statusDot = document.getElementById('status-dot');
                    const statusText = document.getElementById('status-text');
                    const statusDetail = document.getElementById('status-detail');
                    
                    // 清除所有状态类
                    statusDot.className = 'status-dot';
                    
                    // 根据状态设置样式
                    if (statusData.status === 'online' || statusData.status === 'ready') {
                        statusDot.classList.add('online');
                        statusText.textContent = '在线';
                        statusDetail.textContent = statusData.status === 'ready' ? '准备就绪' : '已登录';
                        statusDetail.className = 'badge bg-success';
                    } else if (statusData.status === 'waiting_login') {
                        statusDot.classList.add('waiting');
                        statusText.textContent = '等待登录';
                        statusDetail.textContent = '需要扫码';
                        statusDetail.className = 'badge bg-warning';
                    } else {
                        statusDot.classList.add('offline');
                        statusText.textContent = '离线';
                        statusDetail.textContent = statusData.status || '未知';
                        statusDetail.className = 'badge bg-danger';
                    }
                    
                    // 更新机器人信息
                    document.getElementById('bot-nickname').textContent = statusData.nickname || '-';
                    document.getElementById('bot-wxid').textContent = statusData.wxid || '-';
                    document.getElementById('bot-alias').textContent = statusData.alias || '-';
                    
                    // 如果有设备信息则显示
                    if (statusData.device_name) {
                        document.getElementById('bot-device').textContent = statusData.device_name;
                    }
                    
                    // 如果有登录时间则显示
                    if (statusData.login_time) {
                        const loginTime = new Date(statusData.login_time * 1000);
                        document.getElementById('login-time').textContent = loginTime.toLocaleString();
                    }
                })
                .catch(error => {
                    console.error('获取状态失败:', error);
                    // 使用固定信息作为备用
                    document.getElementById('bot-nickname').textContent = '小球子';
                    document.getElementById('bot-wxid').textContent = 'wxid_l5im9jaxhr4412';
                    
                    const statusDot = document.getElementById('status-dot');
                    statusDot.className = 'status-dot online';
                    document.getElementById('status-text').textContent = '在线';
                    document.getElementById('status-detail').textContent = '已登录';
                    document.getElementById('status-detail').className = 'badge bg-success';
                });
        }
        
        // 获取系统状态
        function getSystemStatus() {
            fetch('/api/system/status')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data) {
                        const systemData = data.data;
                        
                        // 更新运行时间
                        document.getElementById('uptime-value').textContent = systemData.uptime;
                        document.getElementById('start-time').textContent = '启动于 ' + systemData.start_time;
                        
                        // 更新内存使用
                        const memoryUsed = (systemData.memory_used / (1024 * 1024 * 1024)).toFixed(2);
                        const memoryTotal = (systemData.memory_total / (1024 * 1024 * 1024)).toFixed(2);
                        document.getElementById('memory-value').textContent = `${memoryUsed}GB / ${memoryTotal}GB`;
                        const memoryBar = document.querySelector('.progress-bar.bg-purple');
                        memoryBar.style.width = systemData.memory_percent + '%';
                        memoryBar.setAttribute('aria-valuenow', systemData.memory_percent);
                        
                        // 更新CPU使用
                        document.getElementById('cpu-value').textContent = systemData.cpu_percent + '%';
                        const cpuBar = document.querySelector('.progress-bar.bg-warning');
                        cpuBar.style.width = systemData.cpu_percent + '%';
                        cpuBar.setAttribute('aria-valuenow', systemData.cpu_percent);
                        
                        // 更新磁盘使用
                        document.getElementById('disk-value').textContent = systemData.disk_percent + '%';
                        const diskBar = document.querySelector('.progress-bar.bg-success');
                        diskBar.style.width = systemData.disk_percent + '%';
                        diskBar.setAttribute('aria-valuenow', systemData.disk_percent);
                        
                        // 更新最后更新时间
                        document.getElementById('last-updated').textContent = '最后更新: ' + new Date().toLocaleTimeString();
                    }
                })
                .catch(error => {
                    console.error('获取系统状态失败:', error);
                });
        }
        
        // 获取系统日志
        function getSystemLogs() {
            const logViewer = document.getElementById('log-viewer');
            const logLevel = document.getElementById('log-level').value;
            const logLevelParam = logLevel !== 'all' ? `?log_level=${logLevel}` : '';
            
            // 显示加载中提示
            logViewer.innerHTML = '<div class="text-center p-3"><i class="bi bi-hourglass-split me-2"></i>正在加载日志...</div>';
            
            fetch(`/api/system/logs${logLevelParam}`)
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        logViewer.innerHTML = `<div class="text-center p-3 text-danger"><i class="bi bi-exclamation-triangle me-2"></i>${data.error || '获取日志失败'}</div>`;
                        return;
                    }
                    
                    if (!data.logs || data.logs.length === 0) {
                        logViewer.innerHTML = '<div class="text-center p-3 text-warning"><i class="bi bi-info-circle me-2"></i>没有找到日志内容</div>';
                        
                        // 更新日志文件下拉菜单
                        updateLogFileSelect(data.log_files || [], data.current_log || '');
                        return;
                    }
                    
                    // 清空日志查看器
                    logViewer.innerHTML = '';
                    
                    // 添加每行日志
                    data.logs.forEach(log => {
                        const logLine = document.createElement('div');
                        logLine.className = `log-line ${log.level || 'info'}`;
                        
                        // 格式化日志内容
                        let content = '';
                        if (log.timestamp) {
                            content += `${log.timestamp} | `;
                        }
                        
                        if (log.level) {
                            content += `${log.level.toUpperCase()} | `;
                        }
                        
                        content += log.message || log.raw;
                        logLine.textContent = content;
                        
                        logViewer.appendChild(logLine);
                    });
                    
                    // 滚动到底部
                    logViewer.scrollTop = logViewer.scrollHeight;
                    
                    // 更新日志文件下拉菜单
                    updateLogFileSelect(data.log_files || [], data.current_log || '');
                    
                    // 更新最后更新时间
                    document.getElementById('last-log-update').textContent = new Date().toLocaleTimeString();
                })
                .catch(error => {
                    console.error('获取日志失败:', error);
                    logViewer.innerHTML = `<div class="text-center p-3 text-danger"><i class="bi bi-exclamation-triangle me-2"></i>获取日志出错: ${error.message}</div>`;
                });
        }
        
        // 更新日志文件选择下拉菜单
        function updateLogFileSelect(logFiles, currentLog) {
            const logFileSelect = document.getElementById('log-file');
            if (!logFileSelect) return;
            
            // 保存当前选中的值
            const currentSelected = logFileSelect.value;
            
            // 清空选项
            logFileSelect.innerHTML = '';
            
            // 添加找到的日志文件
            logFiles.forEach(file => {
                const option = document.createElement('option');
                option.value = file;
                option.textContent = file;
                option.selected = (file === currentLog || file === currentSelected);
                logFileSelect.appendChild(option);
            });
            
            // 如果没有选项，添加一个默认的
            if (logFiles.length === 0) {
                const option = document.createElement('option');
                option.value = '';
                option.textContent = '-- 无可用日志 --';
                logFileSelect.appendChild(option);
            }
        }
        
        // 初始化 - 调用getSystemInfo函数获取系统信息
        getSystemInfo();
        updateBotStatus();
        getSystemStatus();
        getSystemLogs(); // 添加调用日志获取函数
        
        // 定时刷新
        setInterval(updateBotStatus, 30000);
        setInterval(getSystemStatus, 30000);
        setInterval(getSystemInfo, 30000); 
        setInterval(getSystemLogs, 60000); // 每分钟刷新一次日志
        
        // 刷新系统信息按钮
        document.getElementById('btn-refresh-system').addEventListener('click', function() {
            getSystemInfo(); // 添加获取系统信息的调用
            getSystemStatus();
            this.classList.add('animate__animated', 'animate__rotateIn');
            setTimeout(() => {
                this.classList.remove('animate__animated', 'animate__rotateIn');
            }, 1000);
        });
        
        // 刷新日志按钮
        document.getElementById('btn-refresh-logs').addEventListener('click', function() {
            getSystemLogs(); // 调用获取日志的函数
            this.classList.add('animate__animated', 'animate__rotateIn');
            setTimeout(() => {
                this.classList.remove('animate__animated', 'animate__rotateIn');
            }, 1000);
        });
        
        // 退出登录按钮
        document.getElementById('btn-logout').addEventListener('click', function() {
            if (confirm('确定要退出微信登录吗？')) {
                // 这里可以添加退出登录的代码
                alert('退出登录功能待实现');
            }
        });
        
        // 显示二维码按钮
        document.getElementById('btn-show-qrcode').addEventListener('click', function() {
            window.location.href = '/qrcode';
        });
        
        // 重启系统按钮
        document.getElementById('btn-restart').addEventListener('click', function() {
            if (confirm('确定要重启系统吗？这将断开所有连接。')) {
                // 这里可以添加重启系统的代码
                alert('重启功能待实现');
            }
        });
        
        // 检查更新按钮
        document.getElementById('btn-update').addEventListener('click', function() {
            // 这里可以添加检查更新的代码
            alert('检查更新功能待实现');
        });
        
        // 日志筛选
        document.getElementById('log-level').addEventListener('change', function() {
            getSystemLogs(); // 调用获取日志的函数，将应用选择的筛选级别
        });
        
        document.getElementById('log-file').addEventListener('change', function() {
            // 这里暂时没有实现切换日志文件的功能，可以在未来扩展
            getSystemLogs();
        });
        
        // 复制日志
        document.getElementById('btn-copy-logs').addEventListener('click', function() {
            const logContent = document.getElementById('log-viewer').innerText;
            navigator.clipboard.writeText(logContent)
                .then(() => {
                    alert('日志已复制到剪贴板');
                })
                .catch(err => {
                    console.error('复制失败:', err);
                    alert('复制失败，请手动复制');
                });
        });
        
        // 下载日志
        document.getElementById('btn-download-logs').addEventListener('click', function() {
            const logContent = document.getElementById('log-viewer').innerText;
            const blob = new Blob([logContent], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'system_log_' + new Date().toISOString().replace(/:/g, '-') + '.txt';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        });

        function formatBytes(bytes) {
            if (!bytes || bytes <= 0) return '未知';
            const units = ['B', 'KB', 'MB', 'GB', 'TB'];
            let i = 0;
            while (bytes >= 1024 && i < units.length - 1) {
                bytes /= 1024;
                i++;
            }
            return bytes.toFixed(2) + ' ' + units[i];
        }

        function updateSystemInfo() {
            fetch('/api/system/info')
                .then(response => response.json())
                .then(response => {
                    if (!response.success) {
                        throw new Error(response.error || '获取系统信息失败');
                    }
                    console.log('系统信息:', response.data); // 添加调试日志
                    const data = response.data;
                    document.getElementById('hostname').textContent = data.hostname || '未知';
                    document.getElementById('platform').textContent = data.platform || '未知';
                    document.getElementById('python_version').textContent = data.python_version || '未知';
                    document.getElementById('cpu_count').textContent = data.cpu_count > 0 ? data.cpu_count + ' 核' : '未知';
                    document.getElementById('memory_total').textContent = formatBytes(data.memory_total);
                    document.getElementById('memory_available').textContent = formatBytes(data.memory_available);
                    document.getElementById('disk_total').textContent = formatBytes(data.disk_total);
                    document.getElementById('disk_free').textContent = formatBytes(data.disk_free);
                    document.getElementById('update_time').textContent = data.time || '未知';

                    const errorDiv = document.getElementById('error_message');
                    errorDiv.style.display = 'none';
                })
                .catch(error => {
                    console.error('获取系统信息失败:', error);
                    const errorDiv = document.getElementById('error_message');
                    errorDiv.textContent = '获取系统信息失败: ' + error.message;
                    errorDiv.style.display = 'block';
                    
                    // 在错误时显示未知
                    document.getElementById('hostname').textContent = '未知';
                    document.getElementById('platform').textContent = '未知';
                    document.getElementById('python_version').textContent = '未知';
                    document.getElementById('cpu_count').textContent = '未知';
                    document.getElementById('memory_total').textContent = '未知';
                    document.getElementById('memory_available').textContent = '未知';
                    document.getElementById('disk_total').textContent = '未知';
                    document.getElementById('disk_free').textContent = '未知';
                    document.getElementById('update_time').textContent = '未知';
                });
        }

        function updateBotInfo() {
            fetch('/api/bot/status')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data) {
                        const botData = data.data;
                        const statusDot = document.getElementById('status-dot');
                        const statusText = document.getElementById('status-text');
                        const statusDetail = document.getElementById('status-detail');
                        
                        // 更新状态指示器
                        if (botData.status === 'online' || botData.status === 'ready') {
                            statusDot.className = 'status-dot online';
                            statusText.textContent = '在线';
                            statusDetail.className = 'badge bg-success';
                        } else if (botData.status === 'offline') {
                            statusDot.className = 'status-dot offline';
                            statusText.textContent = '离线';
                            statusDetail.className = 'badge bg-danger';
                        } else {
                            statusDot.className = 'status-dot waiting';
                            statusText.textContent = '等待登录';
                            statusDetail.className = 'badge bg-warning';
                        }
                        statusDetail.textContent = botData.details || '-';
                        
                        // 更新机器人信息
                        document.getElementById('bot-nickname').textContent = botData.nickname || '-';
                        document.getElementById('bot-wxid').textContent = botData.wxid || '-';
                        document.getElementById('bot-alias').textContent = botData.alias || '-';
                        document.getElementById('bot-device').textContent = botData.device || '-';
                        document.getElementById('login-time').textContent = botData.login_time || '-';
                        
                        // 根据状态控制按钮
                        const logoutBtn = document.getElementById('btn-logout');
                        const qrcodeBtn = document.getElementById('btn-show-qrcode');
                        
                        if (botData.status === 'online' || botData.status === 'ready') {
                            logoutBtn.disabled = false;
                            qrcodeBtn.style.display = 'none';
                        } else {
                            logoutBtn.disabled = true;
                            qrcodeBtn.style.display = 'inline-block';
                        }
                    }
                })
                .catch(error => console.error('获取机器人状态失败:', error));
        }

        // 页面加载时更新系统信息
        document.addEventListener('DOMContentLoaded', () => {
            updateSystemInfo();
            updateBotInfo();
            
            // 定时更新
            setInterval(updateSystemInfo, 60000);  // 每60秒更新一次系统信息
            setInterval(updateBotInfo, 10000);     // 每10秒更新一次机器人状态
            
            // 刷新按钮点击事件
            document.getElementById('btn-refresh-system').addEventListener('click', updateSystemInfo);
            
            // 退出登录按钮点击事件
            document.getElementById('btn-logout').addEventListener('click', () => {
                if (confirm('确定要退出登录吗？')) {
                    fetch('/api/bot/logout', { method: 'POST' })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                alert('已退出登录');
                                updateBotInfo();
                            } else {
                                alert('退出登录失败: ' + data.error);
                            }
                        })
                        .catch(error => alert('退出登录失败: ' + error));
                }
            });
            
            // 显示二维码按钮点击事件
            document.getElementById('btn-show-qrcode').addEventListener('click', () => {
                window.location.href = '/qrcode';
            });
        });

        function updateProgressBar(selector) {
            const bar = document.querySelector(selector);
            if (bar) {
                const value = bar.getAttribute('data-value');
                if (value) {
                    bar.style.width = value + '%';
                    bar.setAttribute('aria-valuenow', value);
                }
            }
        }
        
        function updateAllProgressBars() {
            updateProgressBar('.memory-progress');
            updateProgressBar('.cpu-progress');
            updateProgressBar('.disk-progress');
        }
        
        // 初始化时更新进度条
        updateAllProgressBars();
        
        // 定期更新进度条
        setInterval(updateAllProgressBars, 30000);

        // 终端全屏功能
        document.getElementById('btn-fullscreen-terminal').addEventListener('click', function() {
            const terminalContainer = document.getElementById('terminal-container');
            if (terminalContainer.classList.contains('fullscreen')) {
                // 退出全屏
                terminalContainer.classList.remove('fullscreen');
                terminalContainer.style.height = '500px';
                this.innerHTML = '<i class="bi bi-fullscreen"></i>全屏';
            } else {
                // 进入全屏
                terminalContainer.classList.add('fullscreen');
                terminalContainer.style.height = 'calc(100vh - 150px)';
                this.innerHTML = '<i class="bi bi-fullscreen-exit"></i>退出全屏';
            }
        });

        // 监听iframe加载完成
        document.getElementById('terminal-iframe').addEventListener('load', function() {
            document.getElementById('terminal-loading').style.display = 'none';
        });

        // 终端服务检查
        const checkTerminalButton = document.getElementById('check-terminal');
        const restartTerminalButton = document.getElementById('restart-terminal');
        const terminalStatus = document.getElementById('terminal-status');
        const terminalLog = document.getElementById('terminal-log');
        const terminalLogContent = terminalLog.querySelector('div');
        
        function appendLog(message) {
            const timestamp = new Date().toTimeString().substring(0, 8);
            terminalLogContent.innerHTML += `[${timestamp}] ${message}\n`;
            terminalLogContent.scrollTop = terminalLogContent.scrollHeight;
        }
        
        function showTerminalLog() {
            terminalLog.classList.remove('d-none');
            terminalLogContent.innerHTML = '';
        }
        
        if (checkTerminalButton) {
            checkTerminalButton.addEventListener('click', function() {
                terminalStatus.classList.remove('d-none');
                showTerminalLog();
                appendLog('开始诊断终端服务...');
                
                terminalStatus.innerHTML = `
                    <div class="d-flex align-items-center">
                        <div class="spinner-border spinner-border-sm text-primary me-2" role="status">
                            <span class="visually-hidden">正在检查...</span>
                        </div>
                        <span>正在检查终端服务状态...</span>
                    </div>
                `;
                
                // 运行诊断工具
                fetch('/api/terminal/diagnose')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            appendLog('终端服务诊断完成');
                            
                            if (data.status.running) {
                                terminalStatus.innerHTML = `
                                    <div class="alert alert-success mb-0">
                                        <i class="bi bi-check-circle-fill me-2"></i>
                                        终端服务运行正常，可以通过上方按钮访问
                                    </div>
                                `;
                                appendLog('✅ 终端服务运行正常');
                            } else if (data.status.port_used) {
                                terminalStatus.innerHTML = `
                                    <div class="alert alert-warning mb-0">
                                        <i class="bi bi-exclamation-triangle-fill me-2"></i>
                                        端口3000已被占用，但可能不是WeTTy服务
                                        <button id="force-restart" class="btn btn-sm btn-warning ms-2">强制重启服务</button>
                                    </div>
                                `;
                                appendLog('⚠️ 端口3000已被占用，但可能不是WeTTy服务');
                                
                                // 添加强制重启按钮事件
                                document.getElementById('force-restart').addEventListener('click', function() {
                                    restartTerminal(true);
                                });
                            } else {
                                terminalStatus.innerHTML = `
                                    <div class="alert alert-danger mb-0">
                                        <i class="bi bi-x-circle-fill me-2"></i>
                                        终端服务未运行
                                        <button id="start-terminal" class="btn btn-sm btn-primary ms-2">启动服务</button>
                                    </div>
                                `;
                                appendLog('❌ 终端服务未运行');
                                
                                // 添加启动按钮事件
                                document.getElementById('start-terminal').addEventListener('click', function() {
                                    startTerminal();
                                });
                            }
                            
                            // 显示详细诊断信息
                            data.logs.forEach(log => {
                                appendLog(log);
                            });
                        } else {
                            terminalStatus.innerHTML = `
                                <div class="alert alert-danger mb-0">
                                    <i class="bi bi-x-circle-fill me-2"></i>
                                    诊断终端服务时出错: ${data.error}
                                </div>
                            `;
                            appendLog(`错误: ${data.error}`);
                        }
                    })
                    .catch(err => {
                        terminalStatus.innerHTML = `
                            <div class="alert alert-danger mb-0">
                                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                                诊断请求失败: ${err.message}
                            </div>
                        `;
                        appendLog(`请求失败: ${err.message}`);
                        console.error('终端服务诊断失败:', err);
                    });
            });
        }
        
        // 重启终端服务
        function restartTerminal(force = false) {
            terminalStatus.classList.remove('d-none');
            showTerminalLog();
            appendLog('准备重启终端服务...');
            
            terminalStatus.innerHTML = `
                <div class="d-flex align-items-center">
                    <div class="spinner-border spinner-border-sm text-warning me-2" role="status">
                        <span class="visually-hidden">正在重启...</span>
                    </div>
                    <span>正在重启终端服务...</span>
                </div>
            `;
            
            // 发送重启请求
            fetch('/api/terminal/restart', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ force: force })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        terminalStatus.innerHTML = `
                            <div class="alert alert-success mb-0">
                                <i class="bi bi-check-circle-fill me-2"></i>
                                终端服务重启成功
                            </div>
                        `;
                        appendLog('✅ 终端服务重启成功');
                        
                        // 显示详细日志
                        data.logs.forEach(log => {
                            appendLog(log);
                        });
                    } else {
                        terminalStatus.innerHTML = `
                            <div class="alert alert-danger mb-0">
                                <i class="bi bi-x-circle-fill me-2"></i>
                                重启终端服务失败: ${data.error}
                            </div>
                        `;
                        appendLog(`❌ 重启失败: ${data.error}`);
                    }
                })
                .catch(err => {
                    terminalStatus.innerHTML = `
                        <div class="alert alert-danger mb-0">
                            <i class="bi bi-exclamation-triangle-fill me-2"></i>
                            重启请求失败: ${err.message}
                        </div>
                    `;
                    appendLog(`请求失败: ${err.message}`);
                    console.error('重启终端服务失败:', err);
                });
        }
        
        // 启动终端服务
        function startTerminal() {
            terminalStatus.classList.remove('d-none');
            showTerminalLog();
            appendLog('准备启动终端服务...');
            
            terminalStatus.innerHTML = `
                <div class="d-flex align-items-center">
                    <div class="spinner-border spinner-border-sm text-primary me-2" role="status">
                        <span class="visually-hidden">正在启动...</span>
                    </div>
                    <span>正在启动终端服务...</span>
                </div>
            `;
            
            // 发送启动请求
            fetch('/api/terminal/start', {
                method: 'POST'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        terminalStatus.innerHTML = `
                            <div class="alert alert-success mb-0">
                                <i class="bi bi-check-circle-fill me-2"></i>
                                终端服务启动成功
                            </div>
                        `;
                        appendLog('✅ 终端服务启动成功');
                        
                        // 显示详细日志
                        data.logs.forEach(log => {
                            appendLog(log);
                        });
                    } else {
                        terminalStatus.innerHTML = `
                            <div class="alert alert-danger mb-0">
                                <i class="bi bi-x-circle-fill me-2"></i>
                                启动终端服务失败: ${data.error}
                            </div>
                        `;
                        appendLog(`❌ 启动失败: ${data.error}`);
                    }
                })
                .catch(err => {
                    terminalStatus.innerHTML = `
                        <div class="alert alert-danger mb-0">
                            <i class="bi bi-exclamation-triangle-fill me-2"></i>
                            启动请求失败: ${err.message}
                        </div>
                    `;
                    appendLog(`请求失败: ${err.message}`);
                    console.error('启动终端服务失败:', err);
                });
        }
        
        // 重启按钮事件
        if (restartTerminalButton) {
            restartTerminalButton.addEventListener('click', function() {
                restartTerminal(false);
            });
        }
    });
</script>
{% endblock %} 